/*
 * @Author: 梁辉
 * @Date: 2021-06-15 09:52:08
 * @LastEditors: 梁辉
 * @LastEditTime: 2021-06-15 14:32:21
 * @Description: 
 */

/**
 * @description: 函数防抖
 * @param {Function} func 函数
 * @param {Number} wait 延迟执行毫秒数
 * @param {Boolean} immediate true 表示立即执行，false 表示非立即执行
 * @return {Function}
 */
function debounce(func, wait, immediate) {
    if (typeof func != 'function') {
        throw new TypeError(FUNC_ERROR_TEXT)
    }
    let timer
    return function () {
        let context = this
        let args = arguments
        if (timer) {
            clearTimeout(timer)
        }
        if (immediate) {
            let callNow = !timer
            timer = setTimeout(() => {
                timer = null
            }, wait)
            if (callNow) {
                typeof func === 'function' && func.apply(context, args)
            }
        } else {
            timer = setTimeout(() => {
                typeof func === 'function' && func.apply(context, args)
            }, wait)
        }
    }
}

